/**
 * Provider Controller
 */
patientApp.controller('ProviderCtrl',
    ['$scope', '$filter', '$http', 'ngTableParams',
    function($scope, $filter, $http, ngTableParams)
    {
    	$scope.providers = new Array();
    	$scope.tableParameters = null;
    	$scope.error = false;    	
    	$scope.provider = null;
    	
    	$scope.editingProvider = {
	        fName: "",
	        middleInitial: "",
	        lName: "",
	        phone: "",
	        address1: "",
	        address2: "",
	        city: "",
	        state: "",
	        gender: ""
		}
    	
    	$scope.selectAll = {selected: false};
    	
		$scope.selectedProviders = function() {
			var selectedProviders = new Array();
			for(var provider in $scope.providers) {
				if(typeof($scope.providers[provider].selected) !== 'undefined' && $scope.providers[provider].selected == true) {
					selectedProviders.push($scope.providers[provider]);
				}
			}
			return selectedProviders;
		}
    	
    	$scope.genderOptions = [
    	    {
    	    	label: "Male",
    	    	value: "M"
    	    },
    	    {
    	    	label: "Female",
    	    	value: "F"
    	    }
        ];
    	
    	$scope.init = function() {
            Utility.activateSidebarNav("sidebarNavigation", "#/providers/");
            
            $("#btnSelectAll").on('click', function(e) {
            	$scope.$apply(function() {
	            	if($scope.selectAll.selected) {
	            		$scope.selectAll.selected = false;
	            	}
	            	else {
	            		$scope.selectAll.selected = true;
	            	}
	            	
	            	for(var provider in $scope.providers) {
            			$scope.providers[provider].selected = $scope.selectAll.selected;
            		}
            	});
            });
            
            $("#dlgEditProvider").on('shown.bs.modal', function(e) {
                $("#txtFirstName").focus();
            });
            
            $("#dlgEditProvider").on('hidden.bs.modal', function(e) {
            	$scope.errorMessages = new Array();
            	Utility.resetAngularFormErrors($scope, "editProviderForm");
            });
            
	        $scope.tableParameters = new ngTableParams(
	            {
	                page: 1,
	                count: 10,
	                sorting: {
	                	lName: 'asc'
	                }
	            },
	            {
	                total: $scope.providers.length,
	                getData: function($defer, params) {
	                	var orderedData = params.sorting() ? $filter('orderBy')($scope.providers, params.orderBy()) : $scope.providers;
	                    params.total($scope.providers.length);
	                    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
	                }
	            }
	        );
            
            $scope.refreshProviders();
        }
    	
    	$scope.setProvider = function(provider) {
    		$scope.provider = provider;
    	}
    	
    	$scope.updateSelectAll = function() {
        	var allSelected = true;
        	
        	for(var provider in $scope.providers){
        		if(!$scope.providers[provider].selected) {
        			allSelected = false;
        			break;
        		}
        	}
        	
        	if(allSelected) {
        		$scope.selectAll.selected = true;
        		$("#btnSelectAll").addClass("active");
        	}
        	else {
        		$scope.selectAll.selected = false;
        		$("#btnSelectAll").removeClass("active");
        	}
        }
    	
    	$scope.refreshProviders = function() {
    		$http({
                method: "GET",
                url: "/PatientFirst/services/providerservice/providers"
            }).success(
                function(responseModel, status, headers, config) {
                    if(responseModel.status == Utility.jsonResponse.SUCCESS) {
                        $scope.providers = responseModel.data;
                        if($scope.tableParameters != null) {
                            $scope.tableParameters.reload();
                        }
                    }
                    else {
                        Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> An exception occurred while trying to load data: " + responseModel.message);
                    }
                }
            ).error(
                function(data, status, headers, config) {
                    Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> An attempt to load data has failed.");
                }
            );
    	}
    	
    	$scope.createProvider = function() {
        	$scope.providerId = -1;
        	
        	$scope.provider = null;
            $scope.mode = "New";
            $scope.editingProvider.fName = "";
            $scope.editingProvider.middleInitial = "";
            $scope.editingProvider.lName = "";
            $scope.editingProvider.phone = "";
            $scope.editingProvider.address1 = "";
            $scope.editingProvider.address2 = "";
            $scope.editingProvider.city = "";
            $scope.editingProvider.state = "";
            $scope.editingProvider.gender = "";
        }
    	
    	$scope.editProvider = function(providerId) {
    		$scope.mode = "Edit";
    		for(var provider in $scope.providers) {
    			if($scope.providers[provider].id == providerId) {
    				$scope.editingProvider.provider = $scope.providers[provider];
    				$scope.editingProvider.fName = $scope.providers[provider].fName;
    				$scope.editingProvider.middleInitial = $scope.providers[provider].middleInitial;
    				$scope.editingProvider.lName = $scope.providers[provider].lName;
    				$scope.editingProvider.phone = $scope.providers[provider].phone;
    				$scope.editingProvider.address1 = $scope.providers[provider].address1;
    				$scope.editingProvider.address2 = $scope.providers[provider].address2;
    				$scope.editingProvider.city = $scope.providers[provider].city;
    				$scope.editingProvider.state = $scope.providers[provider].state;
    				$scope.editingProvider.gender = $scope.providers[provider].gender;
    				
    				break;
    			}
    		}
    	}
        
    	$scope.deleteProviders = function() {
        	var selectedProviders = $scope.selectedProviders();
        	for(var provider in selectedProviders) {
        		$scope.deleteProvider(selectedProviders[provider]);
        	}
        }
    	
    	$scope.deleteProvider = function(provider) {
    		var providerDeleted = provider;
    		
    		if(typeof(providerDeleted) === 'undefined' || providerDeleted == null) {
    			providerDeleted = $scope.provider;
    		}
    		
    		$http({
    			method: "DELETE",
    			url: "/PatientFirst/services/providerservices/provider/delete/" + providerDeleted.id,
    			providerName: providerDeleted.lName + ", " + providerDeleted.fName,
	            patientId: providerDeleted.id
    		}).success(
				function(responseModel, status, headers, config) {
					if(responseModel.status == Utility.jsonResponse.SUCCESS) {
						for(var i = 0; i < $scope.providers.length; i++) {
							if($scope.providers[i].id == config.providerId) {
								$scope.providers.splice(i, 1);
								$scope.tableParameters.reload();
								break;
							}
						}
						
						Utility.showAlert("alertContainer", "success", true, 3, "<strong>Success!</strong> [" + config.providerName + "] was successfully deleted.");
					}
					else {
						Utility.showAlert("alertContainer", "danger", true, 3, "<strong>Error!</strong> [" + config.providerName + "] could not be deleted. Error Message: " + responseModel.message);
					}
				}
			).error(
				function(responseModel, status, headers, config) {
					Utility.showAlert("alertContainer", "danger", true, 3, "<strong>System Error!</strong> Deletion of [" + config.patientName + "] failed.");
				}
			);
    	}
    	
    	$scope.saveProvider = function() {
    		if($scope.provider != null) {
        		$scope.provider.fName = $scope.editingProvider.fName;
        		$scope.provider.middleInitial = $scope.editingProvider.middleInitial;
        		$scope.provider.lName = $scope.editingProvider.lName;
        		$scope.provider.phone = $scope.editingProvider.phone;
        		$scope.provider.address1 = $scope.editingProvider.address1;
        		$scope.provider.address2 = $scope.editingProvider.address2;
        		$scope.provider.city = $scope.editingProvider.city;
        		$scope.provider.state = $scope.editingProvider.state;
        		$scope.provider.gender = $scope.editingProvider.gender;
        	}
        	else {
        	    var newProvider = {
    	            id: -1,
        	        fName: $scope.editingProvider.fName,
        	        middleInitial: $scope.editingProvider.middleInitial,
        	        lName: $scope.editingProvider.lName,
        	        phone: $scope.editingProvider.phone,
        	        address1: $scope.editingProvider.address1,
        	        address2: $scope.editingProvider.address2,
        	        city: $scope.editingProvider.city,
        	        state: $scope.editingProvider.state,
        	        gender: $scope.editingProvider.gender
        	    }
        	    
        	    if($scope.validateForm()) {
        	    	
        	    }
        	}
    	}
    	
    	$scope.validateForm = function() {
    	    $scope.errorMessages = Utility.getAngularFormErrors($scope, "editProviderForm");
    	    return ($scope.errorMessages.length == 0);
    	}
    	
        $scope.init();
    }
]);